package com.mazewei.dev.controller;

import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 文件下载控制器
 * 处理Excel文件的下载请求
 */
@RestController
@RequestMapping("/api")
public class DownloadController {
    
    private static final Logger logger = LoggerFactory.getLogger(DownloadController.class);
    private static final String OUTPUT_DIR = "output";
    
    /**
     * 下载处理后的Excel文件
     * @param filename 文件名
     * @return 文件资源
     */
    @GetMapping("/download/{filename:.+}")
    public ResponseEntity<Resource> downloadFile(@PathVariable String filename) {
        try {
            // 构建文件路径
            String projectRoot = System.getProperty("user.dir");
            Path filePath = Paths.get(projectRoot, OUTPUT_DIR, filename);
            
            logger.info("[文件下载请求] 文件名: {}, 完整路径: {}", filename, filePath.toString());
            
            // 检查文件是否存在
            File file = filePath.toFile();
            if (!file.exists() || !file.isFile()) {
                logger.warn("[文件下载失败] 文件不存在: {}", filePath.toString());
                return ResponseEntity.notFound().build();
            }
            
            // 创建资源
            Resource resource = new UrlResource(filePath.toUri());
            
            if (!resource.exists() || !resource.isReadable()) {
                logger.warn("[文件下载失败] 文件不可读: {}", filePath.toString());
                return ResponseEntity.notFound().build();
            }
            
            // 设置响应头
            String contentType = "application/vnd.ms-excel";
            
            // 如果是xlsx文件，使用对应的MIME类型
            if (filename.toLowerCase().endsWith(".xlsx")) {
                contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            }
            
            logger.info("[文件下载成功] 文件: {}, 大小: {} bytes, 类型: {}", filename, file.length(), contentType);
            
            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(contentType))
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
                    .body(resource);
                    
        } catch (MalformedURLException e) {
            logger.error("[文件下载异常] URL格式错误: {}", filename, e);
            return ResponseEntity.badRequest().build();
        } catch (Exception e) {
            logger.error("[文件下载异常] 处理文件下载时发生错误: {}", filename, e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 检查文件是否存在
     * @param filename 文件名
     * @return 文件状态
     */
    @GetMapping("/download/check/{filename:.+}")
    public ResponseEntity<Object> checkFile(@PathVariable String filename) {
        try {
            String projectRoot = System.getProperty("user.dir");
            Path filePath = Paths.get(projectRoot, OUTPUT_DIR, filename);
            File file = filePath.toFile();
            
            if (file.exists() && file.isFile()) {
                return ResponseEntity.ok().body(java.util.Map.of(
                    "exists", true,
                    "filename", filename,
                    "size", file.length(),
                    "lastModified", file.lastModified()
                ));
            } else {
                return ResponseEntity.ok().body(java.util.Map.of(
                    "exists", false,
                    "filename", filename
                ));
            }
        } catch (Exception e) {
            logger.error("[文件检查异常] 检查文件时发生错误: {}", filename, e);
            return ResponseEntity.internalServerError().body(java.util.Map.of(
                "error", "检查文件时发生错误: " + e.getMessage()
            ));
        }
    }
}